<template>
  <view>
    <form @submit="formSubmit">
      <view>
        <label>mid:</label>
        <input type="number" v-model="formData.mid" />
      </view>
      <view>
        <label>usetime:</label>
        <input type="text" v-model="formData.usetime" />
      </view>
      <view>
        <label>time:</label>
        <input type="text" v-model="formData.time" />
      </view>
      <view>
        <label>remake:</label>
        <input type="text" v-model="formData.remake" />
      </view>
      <view>
        <button type="default" @click="chooseImage">选择图片</button>
        <view v-for="(image, index) in images" :key="index">
          <image :src="image" mode="widthFix" style="width: 100px; height: 100px;"></image>
          <button @click="removeImage(index)">移除</button>
        </view>
      </view>
      <button form-type="submit">提交</button>
    </form>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        formData: {
          mid: 2,
          usetime: '2.5h',
          time: '2023-12-01 09:56:11',
          remake: 'wu'
        },
        images: [], // 用于存储选中的图片列表
      }
    },
    methods: {
      // 选择图片
      chooseImage() {
        uni.chooseImage({
          success: (res) => {
            if (res.tempFilePaths.length > 0) {
              // 将选中的图片添加到 images 数组中
              this.images = this.images.concat(res.tempFilePaths);
            }
          }
        });
      },
      // 移除图片
      removeImage(index) {
        this.images.splice(index, 1);
      },
      // 提交表单
      formSubmit() {
        // 首先上传图片
        const uploadTasks = this.images.map((image, index) => {
          return this.uploadImage(image, index);
        });

        Promise.all(uploadTasks).then(results => {
          // 所有图片上传完毕后，提交表单数据
          const pictures = results.map(res => res.data); // 假设上传后台返回文件的url路径
          const submitData = {
            ...this.formData,
            pictures: pictures,
          };
          console.log('提交的表单数据', submitData);
          // 这里执行你的表单提交逻辑，例如提交到后台API
        }).catch(error => {
          console.error('图片上传失败', error);
        });
      },
      // 上传单张图片
      uploadImage(imagePath, index) {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: '/achieve/add', // 替换为你的图片上传接口地址
            filePath: imagePath,
            name: 'file', // 后端通过这个字段接收文件
            header: {
                        'content-type': 'multipart/form-data',
                  },
           formData: {
             mid: 2,
             usetime: '2.5h',
             time: '2023-12-01 09:56:11',
             remake: 'wu'
           },
            success: (res) => {
              resolve(JSON.parse(res.data));
            },
            fail: (error) => {
              reject(error);
            }
          });
        });
      }
    }
  }
</script>